package com.ms3ds.deviceData.controller;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.sql.Date;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.ms3ds.deviceData.service.IMiningRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.ms3ds.common.log.annotation.Log;
import com.ms3ds.common.log.enums.BusinessType;
import com.ms3ds.common.security.annotation.RequiresPermissions;
import com.ms3ds.deviceData.domain.SensorData;
import com.ms3ds.deviceData.service.ISensorDataService;
import com.ms3ds.common.core.web.controller.BaseController;
import com.ms3ds.common.core.web.domain.AjaxResult;
import com.ms3ds.common.core.utils.poi.ExcelUtil;
import com.ms3ds.common.core.web.page.TableDataInfo;
import com.ms3ds.deviceData.domain.vo.SensorDataVO;
import com.ms3ds.deviceData.domain.vo.WaterPumpDataVO;
import com.ms3ds.deviceData.domain.vo.AreaSensorDataVO;
import com.ms3ds.deviceData.domain.vo.BatteryDataVO;
import com.ms3ds.common.core.domain.R;

/**
 * 传感器数据Controller
 * 
 * @author zlw
 * @date 2025-09-21
 */
@RestController
@RequestMapping("/sensorData")
public class SensorDataController extends BaseController
{
    @Autowired
    private ISensorDataService sensorDataService;

    @Autowired
    private IMiningRecordService miningRecordService;


    /**
     * 查询传感器数据列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SensorData sensorData)
    {
        startPage();
        List<SensorDataVO> list = sensorDataService.selectSensorDataVOList(sensorData);
        return getDataTable(list);
    }

    /**
     * 导出传感器数据列表
     */
    @Log(title = "传感器数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SensorData sensorData)
    {
        List<SensorDataVO> list = sensorDataService.selectSensorDataVOList(sensorData);
        ExcelUtil<SensorDataVO> util = new ExcelUtil<SensorDataVO>(SensorDataVO.class);
        util.exportExcel(response, list, "传感器数据数据");
    }

    /**
     * 获取传感器数据详细信息
     */
    @GetMapping(value = "/info/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sensorDataService.selectSensorDataById(id));
    }

    /**
     * 新增传感器数据
     */
    @Log(title = "传感器数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SensorData sensorData)
    {
        return toAjax(sensorDataService.insertSensorData(sensorData));
    }

    /**
     * 修改传感器数据
     */
    @Log(title = "传感器数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SensorData sensorData)
    {
        return toAjax(sensorDataService.updateSensorData(sensorData));
    }

    /**
     * 删除传感器数据
     */
    @Log(title = "传感器数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sensorDataService.deleteSensorDataByIds(ids));
    }

    /**
     * 访问时生成传感器数据
     */
//    @Log(title = "生成传感器假数据", businessType = BusinessType.INSERT)
    @PostMapping("/generateFakeData")
    public R<Boolean> generateFakeData()
    {
        return sensorDataService.generateTodayFakeData();
    }

    /**
     * 获取指定矿山7天的风机电耗和产量数据
     * 根据mineId查询风机电耗数据和产量数据，返回BatteryDataVO格式
     */
    @GetMapping("/battery")
    public R<BatteryDataVO> battery(@RequestParam Long mineId)
    {
        try {
            // 1. 获取7天的风机电耗数据
            List<Map<String, Object>> electricData = sensorDataService.getMineSevenDayWindTurbineElectricData(mineId);
            
            // 2. 获取7天的产量数据
            List<Float> yieldData = miningRecordService.getMiningRecordSevenDaySum(mineId);
            
            // 3. 构造返回数据
            List<Integer> yield = new ArrayList<>();
            List<Double> day = new ArrayList<>(); 
            List<Integer> electric = new ArrayList<>();
            
            // 处理电量数据
            for (Map<String, Object> data : electricData) {
                Date date = (Date) data.get("date");
                Double electricValue = (Double) data.get("electric_value");
                
                // 转换日期格式为数字 (例如: 6.5)
                LocalDate localDate = date.toLocalDate();
                double dayValue = Double.parseDouble(localDate.getMonthValue() + "." + localDate.getDayOfMonth());
                day.add(dayValue);
                
                // 电量数据，转换为整数，如果为null则设为0
                electric.add(electricValue != null ? electricValue.intValue() : 0);
            }
            
            // 处理产量数据，转换Float到Integer
            if (yieldData != null && !yieldData.isEmpty()) {
                for (Float yieldValue : yieldData) {
                    yield.add(yieldValue != null ? yieldValue.intValue() : 0);
                }
            }
            
            // 确保三个列表长度一致（都应该是7天的数据）
            // 如果电量数据和产量数据长度不一致，用0补充
            int expectedSize = Math.max(7, Math.max(day.size(), electric.size()));
            while (yield.size() < expectedSize) yield.add(0);
            while (day.size() < expectedSize) {
                // 如果缺少日期，生成默认日期格式
                day.add(0.0);
            }
            while (electric.size() < expectedSize) electric.add(0);
            
            BatteryDataVO batteryDataVO = new BatteryDataVO(yield, day, electric);
            return R.ok(batteryDataVO);
            
        } catch (Exception e) {
            return R.fail("获取矿山电量和产量数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取ABC三个区域的水泵流量数据
     * 查询条件：区域名称包含A、B、C，设备名称为'水泵'，传感器名称为'水泵流量'且状态为1
     */
    @GetMapping("/water")
    public R<WaterPumpDataVO> water()
    {
        try {
            // 查询ABC三个区域的水泵流量数据
            WaterPumpDataVO waterPumpData = sensorDataService.getWaterPumpFlowDataFromABCAreas();
            return R.ok(waterPumpData);
        } catch (Exception e) {
            return R.fail("获取水泵传感器数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取指定矿山的固定传感器当日统计数据
     * 包括：风机的主通风机风压和风机电耗、风速测量仪的巷道风速、水泵的水泵流量
     */
    @GetMapping("/equipInfo/statisticData")
    public List<AreaSensorDataVO> getMineAreaSensorDailyData(@RequestParam Long mineId)
    {
        try {
            // 查询指定矿山的固定传感器当日统计数据
            List<AreaSensorDataVO> result = sensorDataService.getMineAreaSensorDailyData(mineId);
            return result != null ? result : new ArrayList<>();
        } catch (Exception e) {
            // 发生异常时返回空数组
            e.printStackTrace();
            return new ArrayList<>();
        }
    }


}
